declare const window: any;

interface UserProps {
  id: string;        // 用户 ID
  Stage: string;     // 学段
  Subject: string;   // 学科
  Level: number;     // 用户等级
}

export type FridayAction = {
  name: string;
  props?: object;
}

class FridayReporter {
  static appId = window.fridayAppId;

  constructor() {
    this.init();
  }

  public init = () => {
    window._faq = window._faq || [];

    const u = "https://friday.cvte.com/agent/sdk/js/v2/fa.js?_appId=" + window.fridayAppId;
    const d = document;
    const g = d.createElement('script');
    const s = d.getElementsByTagName('script')[0];
    g.type = 'text/javascript';g.async=true; g.defer=true;
    g.src = u;
    s.parentNode.insertBefore(g,s);

    if (!!window['Friday_User_Info'] && typeof window['Friday_User_Info'] === 'object') {
      this.setUser(window['Friday_User_Info']);
    }
  }

  // 设置用户信息 去重
  public setUser = (data: UserProps) => {
    window._faq.push(['setUser', data]);
  }

  public push = (name: string, specialProps: object = {}) => {
    const reportProps = {
      ...specialProps,
    };
    this.dataReportAsync(name, reportProps);
  }

  /**
   * @see http://doc.psd.gz.cvte.cn/friday-doc/JS_SDK.html
   * 立即提交(同步调用的方法)
   * 建议仅用于窗口/页面 "即将关闭" 或 "可能被关闭" 时调用
   */
  public flush = (actions: FridayAction | FridayAction[]) => {
    if (Array.isArray(actions)) {
      actions.forEach(it => {
        this.push(it.name, it.props);
      });
    } else {
      this.push(actions.name, actions.props);
    }
    window['$fa']?.flush();
  }

   // 数据上报入口 异步
   private dataReportAsync = (name: string, params: object) => {
    window._faq.push([
      'trackEvent',
      name,
      {
        ...params,
      },
      FridayReporter.appId,
    ]);
  }
}

export default new FridayReporter();